package com.byx.chatclient.im;

import android.util.Log;

import com.byx.imclientutil.config.ImProperties;
import com.byx.imclientutil.entity.BaseMessage;
import com.byx.imclientutil.factory.ImServiceFactory;
import com.byx.imclientutil.listener.OnMessageStatusListener;
import com.byx.imclientutil.protobuf.ChatMessageProtobuf;
import com.byx.imclientutil.service.ImServiceClient;

/**
 * ImClientBoot
 * 启动类
 * @author Superb
 * @date 2021/4/5 11:17
 */
public class ImClientBoot {
    private static final String TAG= ImClientBoot.class.getSimpleName();
    private static final ImClientBoot INSTANCE = new ImClientBoot();
    private ImServiceClient imServiceClient;
    private boolean isActive;

    public static ImClientBoot getInstance() {
        return INSTANCE;
    }

    public void setOnMessageStatusListener(OnMessageStatusListener onMessageStatusListener) {
        imServiceClient.bindOnMessageStatusListener(onMessageStatusListener);
    }

    public synchronized void init(ImProperties imProperties, int appStatus){
        if (!isActive()){
            if (imProperties == null || imProperties.getHost().isEmpty() || imProperties.getPort() == 0){
                Log.e(TAG, "init: 配置信息不全");
                return;
            }
            isActive = true;
            if (null != imServiceClient){
                imServiceClient.release();
            }
            imServiceClient = ImServiceFactory.getImService();
            updateAppStatus(appStatus);
            imServiceClient.initialize(imProperties,new ImConnectStatusListener());
            System.out.println("服务启动完成，准备连接服务器");
        }
    }

    public synchronized void connect(String userId){
        if (isActive()){
            System.out.println(imServiceClient);
            if (imServiceClient != null && !imServiceClient.isClosed()){
                imServiceClient.connect(new ImEventListener(userId));
                System.out.println("已经连接上服务器");
            }else {
                Log.e(TAG, "connect: imClient还未启动！");
            }
        }
    }

    public void close(){
        if (null != imServiceClient){
            if (!isActive()){
                return;
            }
            imServiceClient.release();
            isActive = false;
        }
    }

    public boolean isActive() {
        return isActive;
    }

    /**
     * 发送消息
     *
     * @param msg
     */
    public void sendMessage(ChatMessageProtobuf.Msg msg) {
        if (isActive) {
            imServiceClient.sendMessage(msg);
        }
    }

    /**
     * 发送消息
     *
     * @param baseMessage
     */
    public void sendMessage(BaseMessage baseMessage) {
        if (isActive) {
            imServiceClient.sendMessage(MessageConverter.toMsg(baseMessage));
        }
    }

    public void updateAppStatus(int appStatus) {
        if (imServiceClient == null) {
            return;
        }

        imServiceClient.setAppStatus(appStatus);
    }
}
